﻿using BroadGoalComponents.BGControls.Toast;
using BroadGoalComponents.Dialogs;
using Custom.Business.Health;
using Custom.Business.Sale;
using Custom.Controls;
using Custom.Framework;
using Custom.Model.Entity;
using Custom.Service.Repository;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Custom.Business.Custom
{
    public partial class frmCustomList : frmBase
    {
        private CustomInfoRepository cusDAL = new CustomInfoRepository();

        public frmCustomList()
        {
            InitializeComponent();

            this.bgDataGridView1.TopLeftHeaderCell.Value = "序号";
            this.bgDataGridView1.RowHeadersWidth = 55;
            this.bgDataGridView1.RowHeadersVisible = true;
            this.bgDataGridView1.ShowLineNo = true;
        }

        private void frmCustomList_Load(object sender, EventArgs e)
        {
            this.search();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            this.search();
        }

        /// <summary>
        /// 新增会员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            this.add();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEdit_Click(object sender, EventArgs e)
        {
            List<int> ids = this.bgDataGridView1.GetCheckedId<int>(this.col_chekflag.Name, this.col_id.Name);
            if (ids.Count == 0)
            {
                WarningDialog.Show(this, "请至少选择一条会员信息");
                return;
            }
            else if (ids.Count > 1)
            {
                WarningDialog.Show(this, "只能选择一条会员信息");
                return;
            }

            int cusid = ids[0];

            frmCustomEdit frm = new frmCustomEdit(cusid);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.search();
            }
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnView_Click(object sender, EventArgs e)
        {
            List<int> ids = this.bgDataGridView1.GetCheckedId<int>(this.col_chekflag.Name, this.col_id.Name);
            if (ids.Count == 0)
            {
                WarningDialog.Show(this, "请至少选择一条会员信息");
                return;
            }
            else if (ids.Count > 1)
            {
                WarningDialog.Show(this, "只能选择一条会员信息");
                return;
            }

            int cusid = ids[0];

            frmCustomView frm = new frmCustomView(cusid);
            frm.ShowDialog();
        }

        /// <summary>
        /// 删除会员记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            List<int> ids = this.bgDataGridView1.GetCheckedId<int>(this.col_chekflag.Name, this.col_id.Name);
            if (ids.Count == 0)
            {
                WarningDialog.Show(this, "请至少选择一条会员信息");
                return;
            }

            DialogResult dialogResult = QuestionDialog.Show("是否确认删除？", "数据删除后不可恢复，请谨慎操作！");
            if (dialogResult == DialogResult.Yes)
            {
                this.cusDAL.BatchDelete(ids);
                this.search();
                BGToast.Show("删除完成");
            }
        }

        /// <summary>
        /// 单元格数据格式化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgDataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;

            if (e.ColumnIndex == this.col_level.Index)
            {
                switch (e.Value?.ToString())
                {
                    case "1":
                        e.Value = "一级";
                        break;
                    case "2":
                        e.Value = "二级";
                        break;
                    default:
                        e.Value = "--";
                        break;
                }
            }
            else if (e.ColumnIndex == this.col_sex.Index)
            {
                switch (e.Value?.ToString())
                {
                    case "0":
                        e.Value = "男";
                        break;
                    case "1":
                        e.Value = "女";
                        break;
                    default:
                        e.Value = "--";
                        break;
                }
            }
            else if (e.ColumnIndex == this.col_createtime.Index)
            {
                e.Value = e.Value.ToString();
            }
        }

        /// <summary>
        /// 操作列按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgDataGridView1_ActionButtonClick(object sender, BroadGoalComponents.BGControls.ActionButtonEventArgs e)
        {
            int rowIndex = this.bgDataGridView1.CurrentRow.Index;
            if (rowIndex < 0 || e.ColumnIndex < 0) return;

            switch (e.ButtonName.Trim())
            {
                case "修改":
                    this.edit(rowIndex);
                    break;
                case "查看":
                    this.view(rowIndex);
                    break;
                case "销售":
                    this.showSale(rowIndex);
                    break;
                case "视力":
                    this.showHealth(rowIndex);
                    break;
            }
        }

        /// <summary>
        /// 双击查看客户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgDataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;

            this.view(e.RowIndex);
        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgPagination_Click(object sender, EventArgs e)
        {
            this.search();
        }

        /// <summary>
        /// 总页数更改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgPagination_OnPageSizeChanged(object sender, EventArgs e)
        {
            this.bgPagination.CurrentPage = 1;
            this.search();
        }

        /// <summary>
        /// 窗体尺寸更改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmCustomList_SizeChanged(object sender, EventArgs e)
        {
            this.lbDataCount.Location = new Point(this.bgPagination.Location.X + this.bgPagination.Width + 10, this.lbDataCount.Location.Y);
        }

        /// <summary>
        /// 查询会员
        /// </summary>
        private void search()
        {
            try
            {
                List<CustomInfo> customs = this.cusDAL.GetAll().OrderByDescending(o => o.createtime).ToList();

                // 卡号
                string cardNo = this.txtCardNo.Text.Trim();
                if (!string.IsNullOrEmpty(cardNo))
                {
                    customs = customs.Where(w => w.cardno.Contains(cardNo)).ToList();
                }
                // 姓名
                string realName = this.txtRealName.Text.Trim();
                if (!string.IsNullOrEmpty(realName))
                {
                    customs = customs.Where(w => w.cusname.Contains(realName)).ToList();
                }
                // 联系电话
                string tel = this.txtTel.Text.Trim();
                if (!string.IsNullOrEmpty(tel))
                {
                    customs = customs.Where(w => w.mobile.Contains(tel)).ToList();
                }

                // 显示当前页的数据源
                this.lbDataCount.Text = $"共{customs.Count}条数据";
                // 分页控件数据绑定
                this.bgPagination.TotalPage = (customs.Count - 1) / this.bgPagination.PageSize + 1;
                if (this.bgPagination.CurrentPage >= this.bgPagination.TotalPage)
                {
                    this.bgPagination.CurrentPage = this.bgPagination.TotalPage > 0 ? this.bgPagination.TotalPage : 1;
                }
                this.lbDataCount.Location = new Point(this.bgPagination.Location.X + this.bgPagination.Width + 10, this.lbDataCount.Location.Y);

                // 绑定当前页的数据源
                this.bgDataGridView1.DataSource = customs.Skip(this.bgPagination.PageSize * (this.bgPagination.CurrentPage - 1)).Take(this.bgPagination.PageSize).ToList();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                WarningDetailDialog.Show(this, "查询失败！", ex.Message);
            }
        }

        /// <summary>
        /// 新增会员
        /// </summary>
        private void add()
        {
            frmCustomAdd frm = new frmCustomAdd();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.search();
            }
        }

        /// <summary>
        /// 修改会员
        /// </summary>
        /// <param name="rowIndex"></param>
        private void edit(int rowIndex)
        {
            int cusid = int.Parse(this.bgDataGridView1.Rows[rowIndex].Cells[this.col_id.Name].Value.ToString());

            frmCustomEdit frm = new frmCustomEdit(cusid);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.search();
            }
        }

        /// <summary>
        /// 查看会员
        /// </summary>
        /// <param name="rowIndex"></param>
        private void view(int rowIndex)
        {
            int cusid = int.Parse(this.bgDataGridView1.Rows[rowIndex].Cells[this.col_id.Name].Value.ToString());

            frmCustomView frm = new frmCustomView(cusid);
            frm.ShowDialog();
        }

        /// <summary>
        /// 查看会员
        /// </summary>
        /// <param name="rowIndex"></param>
        private void showSale(int rowIndex)
        {
            int cusid = int.Parse(this.bgDataGridView1.Rows[rowIndex].Cells[this.col_id.Name].Value.ToString());

            frmCusSaleList frm = new frmCusSaleList(cusid);
            frm.ShowDialog();
        }

        /// <summary>
        /// 显示健康维护信息窗体
        /// </summary>
        /// <param name="rowIndex"></param>
        private void showHealth(int rowIndex)
        {
            int cusid = int.Parse(this.bgDataGridView1.Rows[rowIndex].Cells[this.col_id.Name].Value.ToString());

            frmHealth frm = new frmHealth(cusid);
            frm.ShowDialog();
        }

        private void btnReOrder_Click(object sender, EventArgs e)
        {
            if(QuestionDialog.Show(this, "是否确定进行卡号重排？") == DialogResult.Yes)
            { 

                List<CustomInfo> cusList = this.cusDAL.GetAll().OrderBy(o => o.createtime).ToList();

                ProcessManager.Instance.Show(this, cusList.Count, () =>
                {
                    try
                    {
                        for (int i = 0; i < cusList.Count; i++)
                        {
                            CustomInfo c = cusList[i];
                            if (i < 1000)
                            {
                                c.cardno = (i + 1).ToString().PadLeft(3, '0');
                            }
                            else if (i >= 1000 && i < 10000)
                            {
                                c.cardno = (i + 1).ToString().PadLeft(4, '0');
                            }
                            else if (i >= 10000 && i < 100000)
                            {
                                c.cardno = (i + 1).ToString().PadLeft(5, '0');
                            }
                            this.cusDAL.Update(c);

                            ProcessManager.Instance.ReportProgress(i + 1, $"正在进行卡号重排......");
                        }
                        ProcessManager.Instance.CloseAysnc(this);
                        this.Invoke(new Action(() =>
                        {
                            InformationDialog.Show(this, "重排完成！");
                            this.search();
                        }));
                    }
                    catch (Exception ex)
                    {
                        this.Invoke(new Action(() =>
                        {
                            ProcessManager.Instance.CloseAysnc(this);
                            WarningDetailDialog.Show(this, "卡号重排出错，详见日志！", ex.Message);
                        }));
                    }
                });                                
            }
        }
    }
}
